package plugin;

import java.util.Iterator;
import java.util.List;

/**
 * This class is responsible for the Chain of Responsibility logic, and is the Controller's
 * gateway into the product identification plugins.
 * @author Royce
 *
 */
public class ChainManager {

	/**
	 * Default no-arg constructor
	 */
	public ChainManager() {
		
	}
	
	/**
	 * Uses all plugins in the PluginRegistry to find a description for a product.  This will
	 * use the chain of plugins stored in the PluginRegistry to find the description.
	 * @param barcode The String representation of the barcode of the product
	 * @return The description of the product, or an empty string if unable to find
	 * any description.
	 */
	public String identifyProduct(String barcode) {
		List<PluginDescriptor> chain = PluginRegistry.instance().getChain();
		String description = "";
		Iterator<PluginDescriptor> pluginIterator = chain.iterator();
		while(pluginIterator.hasNext()) {
			PluginDescriptor nextDesc = pluginIterator.next();
			try {
				IProductIDPlugin nextPlugin = PluginRegistry.instance().spawnPlugin(nextDesc);
				description = nextPlugin.identifyProduct(barcode);
				break;
			}
			catch (Exception e) {
				//ignore it, move on to the next one
			}	
		}
		return description;
	}
}
